using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FriendsNearby.Services.Entities;
using System.Collections.Generic;
using System.Text;
using FriendsNearby.Services;

namespace FriendsNearby.Fbml
{
    public partial class EditPreferences : System.Web.UI.Page
    {
        FriendsNearbySystem friendsNearbySystem;
        List<VisibilityItem> visibilityItems;
        VisibilityLevel selectedVisibilityLevel;
		IUsersService userService;
        string nearbyRadiusKM;
        string nearbyRadiusKMInvalidMessage = string.Empty;
        string twitterAccountName;
        string twitterFollowMessage;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            visibilityItems = new List<VisibilityItem>();

            visibilityItems.Add(new VisibilityItem(VisibilityLevel.Everyone,"Everyone"));
            visibilityItems.Add(new VisibilityItem(VisibilityLevel.ContactsAndTheirContacts,"Friends and their friends"));
            visibilityItems.Add(new VisibilityItem(VisibilityLevel.OnlyFriends,"Only Friends (Friends of a Friend would know I'm nearby but not my name)"));
            visibilityItems.Add(new VisibilityItem(VisibilityLevel.Nobody,"Nobody"));
                        
            this.saveButton.Click += new EventHandler(SaveButton_Click);
        }


        UserRegistry userPrefsFromDatabase;


        protected void Page_Load(object sender, EventArgs e)
        {
            friendsNearbySystem = new FriendsNearbySystem();
			userService = friendsNearbySystem.GetService<IUsersService>();
			userPrefsFromDatabase = userService.QueryUserRegistry(x => x.FacebookUserId == fbApplication.UserID);

            if (!string.IsNullOrEmpty(Request.Form["visibility"]))
            {
                selectedVisibilityLevel = (VisibilityLevel)int.Parse(Request.Form["visibility"]);
            }
            else
            {
				selectedVisibilityLevel = (VisibilityLevel)userPrefsFromDatabase.VisibilityLevel;
            }


            if (!string.IsNullOrEmpty(Request.Form["radius_km"]))
            {
                nearbyRadiusKM = Request.Form["radius_km"];
            }
            else
            {
				nearbyRadiusKM = Convert.ToString(userPrefsFromDatabase.NearbyRadiusKM);
            }

            if (!string.IsNullOrEmpty(Request.Form["twitter_acc"]))
            {
                twitterAccountName = Request.Form["twitter_acc"];
            }
            else
            {
				twitterAccountName = userPrefsFromDatabase.TwitterScreenName;
            }
        }

        void SaveButton_Click(object sender, EventArgs e)
        {
            //input validation.
            int nearbyRadius = 0;
            if (!string.IsNullOrEmpty(Request.Form["radius_km"]))
            {
                if (!int.TryParse(Request.Form["radius_km"], out nearbyRadius))
                {
                    nearbyRadiusKMInvalidMessage = "The value for nearby radius is invalid. Please enter a numeric value, less than 60000.";
                    return;
                }

                if (nearbyRadius > 60000)
                {
                    nearbyRadiusKMInvalidMessage = "The value for nearby radius is invalid. Please enter a numeric value, less than 60000.";
                    return;
                }
            }
            UserRegistry oldUserPreferences = userPrefsFromDatabase;
            userService.SetUserPreferences(userPrefsFromDatabase.UserID,Request.Form["twitter_acc"], nearbyRadius, (VisibilityLevel) int.Parse(Request.Form["visibility"]));


            // display stored value
			UserRegistry storedUserPreferences = userService.GetUserPreferences(userPrefsFromDatabase.UserID);
            selectedVisibilityLevel = (VisibilityLevel)  storedUserPreferences.VisibilityLevel;
            nearbyRadiusKM = Convert.ToString(storedUserPreferences.NearbyRadiusKM);
            twitterAccountName = storedUserPreferences.TwitterScreenName;

            statusMessage.SetMessage("Preferences Updated");

            if (!String.IsNullOrEmpty(twitterAccountName) && string.Compare(twitterAccountName, oldUserPreferences.TwitterScreenName) != 0)
            {
                twitterFollowMessage = @"
You have updated your twitter alias. <br/>
In order to interact with Contacts Nearby through Twitter, you need to follow the ""fnb"" automated user. <br/><br/>
Please send the following command from your cellphone, or just follow the link to do it from Twitter: <a target=""_blank"" href=""http://twitter.com/home?status=follow fnb"">follow fnb</a>";
            }
            else
            {
                // forward user to default page with 'Preferences Updated' 
                // only if twitter user didn't change
                Context.Items[Default.MESSAGE] = "Preferences Updated";
                Server.Transfer("Default.aspx");
            }            
        }

        public string NearbyRadiusKM
        {
            get { return nearbyRadiusKM; }
        }

        public string NearbyRadiusKMInvalidMessage
        {
            get { return nearbyRadiusKMInvalidMessage; }
        }

        public string TwitterAccountName
        {
            get { return twitterAccountName; }
        }

        public string TwitterFollowMessage
        {
            get { return twitterFollowMessage; }
        }

        public string RenderVisibilityComboItems
        {
            get
            {
                StringBuilder builder = new StringBuilder();
                foreach (VisibilityItem item in visibilityItems)
                {
                    builder.Append("<option value=\"");
                    builder.Append((int) item.Value);
                    builder.Append("\"");
                    if (item.Value == selectedVisibilityLevel)
                    {
                        builder.Append(" selected ");
                    }
                    builder.Append(">");
                    builder.Append(item.Text);
                    builder.Append("</option>");
                }
                return builder.ToString();
            }
        }
    }

    class VisibilityItem
    {
        public VisibilityItem(VisibilityLevel value, string text)
        {
            this.Value = value;
            this.Text = text;
        }

        public VisibilityLevel Value;
        public string Text;
    }
}
